#!/bin/bash

# Larapress App - 批量执行 flutter pub get 脚本
# 此脚本会为所有 larapress_app_package 下的子包执行 flutter pub get

set -e  # 遇到错误时退出

echo "🚀 开始为所有 package 执行 flutter pub get..."

# 获取脚本所在目录的绝对路径
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PACKAGE_DIR="$SCRIPT_DIR/larapress_app_package"

# 检查 larapress_app_package 目录是否存在
if [ ! -d "$PACKAGE_DIR" ]; then
    echo "❌ 错误: larapress_app_package 目录不存在: $PACKAGE_DIR"
    exit 1
fi

# 定义所有需要执行 pub get 的包目录
PACKAGES=(
    "cms"
    "common" 
    "components"
    "theme"
    "user"
)

# 计数器
SUCCESS_COUNT=0
TOTAL_COUNT=${#PACKAGES[@]}

echo "📦 找到 $TOTAL_COUNT 个包需要处理: ${PACKAGES[*]}"
echo ""

# 遍历每个包并执行 flutter pub get
for package in "${PACKAGES[@]}"; do
    package_path="$PACKAGE_DIR/$package"
    
    echo "📁 处理包: $package"
    
    # 检查包目录是否存在
    if [ ! -d "$package_path" ]; then
        echo "⚠️  警告: 包目录不存在，跳过: $package_path"
        continue
    fi
    
    # 检查 pubspec.yaml 是否存在
    if [ ! -f "$package_path/pubspec.yaml" ]; then
        echo "⚠️  警告: pubspec.yaml 不存在，跳过: $package_path"
        continue
    fi
    
    # 进入包目录并执行 flutter pub get
    cd "$package_path"
    
    echo "   🔄 执行 flutter pub get..."
    if flutter pub get; then
        echo "   ✅ $package 执行成功"
        ((SUCCESS_COUNT++))
    else
        echo "   ❌ $package 执行失败"
    fi
    
    echo ""
done

# 返回主目录
cd "$SCRIPT_DIR"

# 输出总结
echo "📊 执行总结:"
echo "   成功: $SUCCESS_COUNT/$TOTAL_COUNT"
echo "   失败: $((TOTAL_COUNT - SUCCESS_COUNT))/$TOTAL_COUNT"

if [ $SUCCESS_COUNT -eq $TOTAL_COUNT ]; then
    echo "🎉 所有包都执行成功！"
    exit 0
else
    echo "⚠️  部分包执行失败，请检查错误信息"
    exit 1
fi
